<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>软件管理后台</title>
    <style>
        * {
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }

        h1 {
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-top: 0;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }

        .search-box {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 300px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }

        .btn-primary {
            background-color: #4285f4;
            color: white;
        }

        .btn-deplay {
            background-color: #66ccff;
            color: white;
        }

        .btn-danger {
            background-color: #ea4335;
            color: white;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th,
        td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f9f9f9;
            font-weight: bold;
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        .icon-cell {
            width: 40px;
        }

        .icon {
            width: 30px;
            height: 30px;
            object-fit: contain;
        }

        .checkbox {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        .action-btns {
            display: flex;
            gap: 5px;
        }

        .action-btn {
            padding: 4px 8px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }

        .edit-btn {
            background-color: #34a853;
            color: white;
        }

        .delete-btn {
            background-color: #ea4335;
            color: white;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 5px;
        }

        .page-btn {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background-color: white;
            cursor: pointer;
            border-radius: 3px;
        }

        .page-btn.active {
            background-color: #4285f4;
            color: white;
            border-color: #4285f4;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            width: 500px;
            max-width: 90%;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-control {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .loading {
            text-align: center;
            padding: 20px;
            font-style: italic;
            color: #666;
        }

        .error {
            color: #ea4335;
            text-align: center;
            padding: 20px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>软件管理</h1>

        <div class="toolbar">
            <div>
                <input type="text" class="search-box" placeholder="搜索软件名称..." id="searchInput">
            </div>
            <div>
                <button class="btn btn-deplay" id="deplay">导出文件</button>
                <button class="btn btn-primary" id="addBtn">添加软件</button>
                <button class="btn btn-danger" id="deleteSelectedBtn">删除选中</button>
            </div>
        </div>

        <table>
            <thead>
                <tr>
                    <th><input type="checkbox" id="selectAll"></th>
                    <th>图标</th>
                    <th>ID</th>
                    <th>软件名称</th>
                    <th>大小</th>
                    <th>类型</th>
                    <th>上传时间</th>
                    <th>短链接</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="appTableBody">
                <tr>
                    <td colspan="9" class="loading">正在加载数据...</td>
                </tr>
            </tbody>
        </table>

        <div class="pagination" id="pagination">
            <!-- 分页将通过JavaScript动态生成 -->
        </div>
    </div>

    <!-- 添加/编辑模态框 -->
    <div class="modal" id="appModal">
        <div class="modal-content">
            <h2 id="modalTitle">添加软件</h2>
            <form id="appForm">
                <input type="hidden" id="appId">
                <div class="form-group">
                    <label for="icon">图标URL</label>
                    <input type="text" class="form-control" id="icon" placeholder="输入图标URL">
                </div>
                <div class="form-group">
                    <label for="name_all">软件全称</label>
                    <input type="text" class="form-control" id="name_all" required placeholder="输入软件全称">
                </div>
                <div class="form-group">
                    <label for="size">软件大小</label>
                    <input type="text" class="form-control" id="size" required placeholder="例如: 15.2MB">
                </div>
                <div class="form-group">
                    <label for="typeis">类型</label>
                    <select class="form-control" id="typeis" required>
                        <option value="">选择类型</option>
                        <option value="安卓">安卓</option>
                        <option value="压缩包">压缩包</option>
                        <option value="Windows">Windows</option>
                        <option value="文档">文档</option>
                        <option value="Linux">Linux</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="time">上传时间</label>
                    <input type="datetime-local" class="form-control" id="time" required>
                </div>
                <div class="form-group">
                    <label for="duan">短链接</label>
                    <input type="text" class="form-control" id="duan" placeholder="输入短链接">
                </div>
                <div class="form-group">
                    <label for="download_url">下载地址</label>
                    <input type="text" class="form-control" id="download_url" required placeholder="输入下载地址">
                </div>
                <div class="form-group">
                    <label for="jianjie">简介</label>
                    <textarea class="form-control" id="jianjie" rows="3" required placeholder="输入软件简介"></textarea>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" id="cancelBtn">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 全局变量
        let appsData = [];
        let currentPage = 1;
        const itemsPerPage = 10;
        let currentEditId = null;

        // DOM元素
        const appTableBody = document.getElementById('appTableBody');
        const appModal = document.getElementById('appModal');
        const appForm = document.getElementById('appForm');
        const modalTitle = document.getElementById('modalTitle');
        const addBtn = document.getElementById('addBtn');
        const deplay = document.getElementById('deplay');
        const cancelBtn = document.getElementById('cancelBtn');
        const selectAll = document.getElementById('selectAll');
        const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
        const searchInput = document.getElementById('searchInput');
        const pagination = document.getElementById('pagination');

        // 从API获取数据
        async function fetchApps() {
            try {
                appTableBody.innerHTML = '<tr><td colspan="9" class="loading">正在加载数据...</td></tr>';

                const response = await fetch('/api/data');
                if (!response.ok) {
                    throw new Error('获取数据失败');
                }

                appsData = await response.json();
                appsData.forEach(app => app.selected = false);

                renderTable(getPaginatedData());
                renderPagination();
            } catch (error) {
                console.error('Error fetching apps:', error);
                appTableBody.innerHTML = '<tr><td colspan="9" class="error">加载数据失败: ' + error.message + '</td></tr>';
            }
        }

        // 获取当前页的数据
        function getPaginatedData() {
            const startIndex = (currentPage - 1) * itemsPerPage;
            return appsData.slice(startIndex, startIndex + itemsPerPage);
        }

        // 渲染表格
        function renderTable(data) {
            if (data.length === 0) {
                appTableBody.innerHTML = '<tr><td colspan="9" class="loading">没有找到数据</td></tr>';
                return;
            }

            appTableBody.innerHTML = '';

            data.forEach(app => {
                const row = document.createElement('tr');

                row.innerHTML = `
                    <td><input type="checkbox" class="checkbox" data-id="${app.id}" ${app.selected ? 'checked' : ''}></td>
                    <td class="icon-cell">
                        ${app.icon ? `<img src="${app.icon}" class="icon" alt="图标">` : '无'}
                    </td>
                    <td>${app.id}</td>
                    <td>${app.name_all}</td>
                    <td>${app.size}</td>
                    <td>${app.typeis}</td>
                    <td>${app.time}</td>
                    <td>${app.duan || '无'}</td>
                    <td class="action-btns">
                        <button class="action-btn edit-btn" data-id="${app.id}">编辑</button>
                        <button class="action-btn delete-btn" data-id="${app.id}">删除</button>
                    </td>
                `;

                appTableBody.appendChild(row);
            });

            // 添加事件监听器
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', () => editApp(parseInt(btn.dataset.id)));
            });

            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', () => deleteApp(parseInt(btn.dataset.id)));
            });

            document.querySelectorAll('.checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', (e) => {
                    const id = parseInt(checkbox.dataset.id);
                    const app = appsData.find(a => a.id === id);
                    if (app) app.selected = e.target.checked;

                    // 更新"全选"状态
                    selectAll.checked = appsData.every(app => app.selected);
                });
            });
        }

        // 渲染分页
        function renderPagination() {
            const totalPages = Math.ceil(appsData.length / itemsPerPage);

            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }

            let html = '';

            // 上一页按钮
            html += `<button class="page-btn" ${currentPage === 1 ? 'disabled' : ''} id="prevPage">&laquo;</button>`;

            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                html += `<button class="page-btn ${i === currentPage ? 'active' : ''}" data-page="${i}">${i}</button>`;
            }

            // 下一页按钮
            html += `<button class="page-btn" ${currentPage === totalPages ? 'disabled' : ''} id="nextPage">&raquo;</button>`;

            pagination.innerHTML = html;

            // 添加事件监听器
            document.querySelectorAll('[data-page]').forEach(btn => {
                btn.addEventListener('click', () => {
                    currentPage = parseInt(btn.dataset.page);
                    renderTable(getPaginatedData());
                    renderPagination();
                });
            });

            document.getElementById('prevPage')?.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    renderTable(getPaginatedData());
                    renderPagination();
                }
            });

            document.getElementById('nextPage')?.addEventListener('click', () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    renderTable(getPaginatedData());
                    renderPagination();
                }
            });
        }

        // 打开添加模态框
        function openAddModal() {
            currentEditId = null;
            modalTitle.textContent = '添加软件';
            appForm.reset();
            appModal.style.display = 'flex';
        }

        // 打开编辑模态框
        function editApp(id) {
            const app = appsData.find(a => a.id === id);
            if (!app) return;

            currentEditId = id;
            modalTitle.textContent = '编辑软件';

            // 填充表单
            document.getElementById('appId').value = app.id;
            document.getElementById('icon').value = app.icon || '';
            document.getElementById('name_all').value = app.name_all;
            document.getElementById('size').value = app.size;
            document.getElementById('typeis').value = app.typeis;
            document.getElementById('time').value = formatDateTimeForInput(app.time);
            document.getElementById('duan').value = app.duan || '';
            document.getElementById('download_url').value = app.download_url;
            document.getElementById('jianjie').value = app.jianjie;

            appModal.style.display = 'flex';
        }

        // 格式化日期时间为input[type=datetime-local]需要的格式
        function formatDateTimeForInput(datetime) {
            if (!datetime) return '';

            // 如果已经是ISO格式，直接返回
            if (datetime.includes('T')) {
                return datetime;
            }

            // 否则尝试解析
            const date = new Date(datetime);
            if (isNaN(date.getTime())) return '';

            const pad = num => num.toString().padStart(2, '0');

            return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
        }

        // 删除软件
        async function deleteApp(id) {
            if (!confirm('确定要删除这个软件吗？')) return;

            try {
                const response = await fetch(`/api/data/${id}`, {
                    method: 'DELETE'
                });

                if (!response.ok) {
                    throw new Error('删除失败');
                }

                // 从本地数据中移除
                const index = appsData.findIndex(a => a.id === id);
                if (index !== -1) {
                    appsData.splice(index, 1);
                }

                // 重新渲染
                renderTable(getPaginatedData());
                renderPagination();

            } catch (error) {
                console.error('Error deleting app:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 删除选中的软件
        async function deleteSelectedApps() {
            const selectedIds = appsData.filter(a => a.selected).map(a => a.id);
            if (selectedIds.length === 0) {
                alert('请先选择要删除的软件');
                return;
            }

            if (!confirm(`确定要删除选中的 ${selectedIds.length} 个软件吗？`)) return;

            try {
                const response = await fetch('/api/data/batch', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ ids: selectedIds })
                });

                if (!response.ok) {
                    throw new Error('批量删除失败');
                }

                // 从本地数据中移除
                selectedIds.forEach(id => {
                    const index = appsData.findIndex(a => a.id === id);
                    if (index !== -1) {
                        appsData.splice(index, 1);
                    }
                });

                // 重新渲染
                renderTable(getPaginatedData());
                renderPagination();
                selectAll.checked = false;

            } catch (error) {
                console.error('Error deleting selected apps:', error);
                alert('批量删除失败: ' + error.message);
            }
        }

        // 保存软件
        async function saveApp(e) {
            e.preventDefault();

            const appData = {
                id: currentEditId || 0, // 0表示新记录
                icon: document.getElementById('icon').value || null,
                name_all: document.getElementById('name_all').value,
                size: document.getElementById('size').value,
                typeis: document.getElementById('typeis').value,
                time: document.getElementById('time').value,
                duan: document.getElementById('duan').value || null,
                download_url: document.getElementById('download_url').value,
                jianjie: document.getElementById('jianjie').value
            };

            try {
                const url = currentEditId ? `/api/data/${currentEditId}` : '/api/data';
                const method = currentEditId ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(appData)
                });

                if (!response.ok) {
                    throw new Error(currentEditId ? '更新失败' : '添加失败');
                }

                const savedApp = await response.json();

                if (currentEditId) {
                    // 更新现有软件
                    const index = appsData.findIndex(a => a.id === currentEditId);
                    if (index !== -1) {
                        appsData[index] = savedApp;
                    }
                } else {
                    // 添加新软件
                    appsData.unshift(savedApp); // 添加到开头
                }

                // 重新渲染
                renderTable(getPaginatedData());
                renderPagination();
                appModal.style.display = 'none';

            } catch (error) {
                console.error('Error saving app:', error);
                alert('保存失败: ' + error.message);
            }
        }

        // 搜索软件
        function searchApps() {
            const searchTerm = searchInput.value.toLowerCase();

            if (!searchTerm) {
                renderTable(getPaginatedData());
                renderPagination();
                return;
            }

            const filteredData = appsData.filter(app =>
                app.name_all.toLowerCase().includes(searchTerm) ||
                (app.jianjie && app.jianjie.toLowerCase().includes(searchTerm)) ||
                (app.typeis && app.typeis.toLowerCase().includes(searchTerm))
            );

            renderTable(filteredData.slice(0, itemsPerPage));
            pagination.innerHTML = ''; // 清空分页
        }
        async function deplay_fn() {
            const response = await fetch('/api/data/deplay');
            if (!response.ok) {
                throw new Error('获取数据失败');
            }
            alert('导出Json文件')
        }

        // 事件监听器
        addBtn.addEventListener('click', openAddModal);
        deplay.addEventListener('click', deplay_fn);
        cancelBtn.addEventListener('click', () => appModal.style.display = 'none');
        appForm.addEventListener('submit', saveApp);

        selectAll.addEventListener('change', (e) => {
            const isChecked = e.target.checked;
            appsData.forEach(app => app.selected = isChecked);
            renderTable(getPaginatedData());
        });

        deleteSelectedBtn.addEventListener('click', deleteSelectedApps);
        searchInput.addEventListener('input', searchApps);

        // 点击模态框外部关闭模态框
        window.addEventListener('click', (e) => {
            if (e.target === appModal) {
                appModal.style.display = 'none';
            }
        });

        // 初始加载数据
        fetchApps();
    </script>
</body>

</html>